<?php
/**
 * Class descript.
 * User: chan
 * Date: 2017/10/26 15:30
 */
namespace app\api\logic;
use think\Cache;
use think\Db;
use think\Request;
use app\api\validate\Login as LoginValidate;
class Login extends \app\api\BaseModel
{
    /*
     *	用户登陆
     */
    public function login()
    {
        (new LoginValidate())->checkLoginParam();

        $tel   = $this->requestData['mobile'];
        $passwd = $this->requestData['password'];

//        if(!empty($tel)&&!empty($passwd)){
            $where['mobile'] = $tel;
            $where['delete'] = 1;
            $root = db('member')->where($where)->find();
            if(!$root){
                return array('message'=>'账号不存在');
            }else{
                if($root['passwd']==md5($passwd)){
                    if($root['status']==0) return array('message'=>'账号禁止登录中');
                    $Oauth2 =  new \app\api\service\Oauth2();
                    $user = [
                        'userId'=> $root['id'],
                        'mobile'=> $root['mobile'],
                        'nickname'  => $root['nickname'],
                        'id'=> $root['id'],
                        'uid'=> $root['id'],
                        'avatar'=> $root['headimage'],
                        'sex' => $root['sex']?$root['sex']:'',
                        'is_qq'=> !empty($root['qq_openid'])?'1':'0',       //是否绑定QQ
                        'is_wx'=> !empty($root['wx_openid'])?'1':'0',       //是否绑定微信
                        'is_wb'=> !empty($root['wb_openid'])?'1':'0',       //是否绑定微博
                        'is_login_type'=> '1',              //登录
                        'height' => $root['height'],
                        'weight' => $root['weight'],
                        'physical_activity' => $root['physical_activity'],
                        'age' => $root['age'],
                        'like_dish' => $root['like_dish'],
                        'dish_type' => $root['dish_type'],
                        'figure' => $root['figure'],
                        'taste' => $root['taste'],
                        'spend_calories' => $root['spend_calories'],
                        'headimage' => $root['headimage'],
                    ];

                    //判断是否注册百川
                    $member_uid = 'member'.$root['id'];
                    $chat_result = db('chat')->where(['userid'=>$member_uid])->find();
                    if(empty($chat_result)){
                        $result = (new \app\api\logic\Chat())->create_user($root['nickname'],'member'.$root['id'],'123456',$root['headimage'],'1',$root['id']);
                        if($result['message'] == '重复的昵称'){
                            $result = (new \app\api\logic\Chat())->create_user(time(),'member'.$root['id'],'123456',$root['headimage'],'1',$root['id']);
                        }
                        if(array_key_exists('message',$result)){
                            return array('message'=>'登陆失败');
                        }

                        $chat_result['userid'] = 'member'.$root['id'];
                        $chat_result['pwd'] = '123456';
                    }

                    $user['baichuan_user'] = $chat_result['userid'];
                    $user['baichuan_password'] = $chat_result['pwd'];

                    //背景图
                    $admin_background_image = db('admin_background_image')->find();
                    $user['background'] = $admin_background_image['background_image'];

                    $tokenInfo = $Oauth2::generateToken($user);
                    return $tokenInfo;
                }else{
                    return array('message'=>'密码错误');
                }
            }
//        }else{
//            return array('message'=>'账号或密码为空');
//        }
    }

    /*
     *  第三方登录
     */
    public function otherlogin()
    {
            $type=$this->requestData['type'];
            if($type==0) {
                $where['wx_openid'] = $this->requestData['openid'];
            }
            if($type==1) {
                $where['qq_openid'] = $this->requestData['openid'];
            }
            if($type==2) {
                $where['wb_openid'] = $this->requestData['openid'];
            }
            $where['delete'] = 1;
            $root = db('member')->where($where)->find();
            if(!$root){

                if(isset($this->requestData['city'])){
                    $where['city']=$this->requestData['city'];
                }
                if(isset($this->requestData['province'])){
                    $where['province']=$this->requestData['province'];
                }
                if(isset($this->requestData['nickname'])){
                    $where['nickname']=$this->requestData['nickname'];
                }
                $where['sex']=$this->requestData['sex'];
                $sex_array = array('1','2');

                if(!in_array($where['sex'], $sex_array)){
                    if($where['sex'] == '男'){
                        $where['sex'] = 1;
                    }

                    if($where['sex'] == '女'){
                        $where['sex'] = 2;
                    }

                    $where['sex'] = 1;
                }

                //昵称检测
                $root = db('member')->where(array('nickname'=>$this->requestData['nickname']))->find();
                if(!empty($root))return array('message'=>'该昵称已被使用!');

                $where['headimage']=$this->requestData['headimgurl'];
                $insert = db('member')->insertGetId($where);
                $member = db('member')->where("id='$insert'")->find();
                $user = [
                    'userId'=> $member['id'],
                    'uid'=> $member['id'],
                    'id'=> $member['id'],
                    'mobile'=> !empty($member['mobile'])?$member['mobile']:'',
                    'is_qq'=> !empty($member['qq_openid'])?'1':'0',
                    'is_wx'=> !empty($member['wx_openid'])?'1':'0',
                    'is_wb'=> !empty($member['wb_openid'])?'1':'0',
                    'is_login_type'=> '2',
                    'nickname'=> $member['nickname'],
                    'avatar'=> $member['headimage'],
                    'sex' => $member['sex']?$member['sex']:'',
                    'height' => $member['height'],
                    'weight' => $member['weight'],
                    'physical_activity' => $member['physical_activity'],
                    'age' => $member['age'],
                    'like_dish' => $member['like_dish'],
                    'dish_type' => $member['dish_type'],
                    'figure' => $member['figure'],
                    'taste' => $member['taste'],
                    'spend_calories' => $member['spend_calories'],
                    'headimage' => $member['headimage'],
                ];
                $Oauth2 =  new \app\api\service\Oauth2();
                $tokenInfo = $Oauth2::generateToken($user);
                return $tokenInfo;
            }else{
                    if($root['status']==0) return array('message'=>'账号禁止登录中');
                    $Oauth2 =  new \app\api\service\Oauth2();
                    $user = [
                        'userId'=> $root['id'],
                        'uid'=> $root['id'],
                        'id'=> $root['id'],
                        'mobile'=> $root['mobile'],
                        'is_qq'=> !empty($root['qq_openid'])?'1':'0',
                        'is_wx'=> !empty($root['wx_openid'])?'1':'0',
                        'is_wb'=> !empty($root['wb_openid'])?'1':'0',
                        'is_login_type'=> '2',
                        'nickname'=> $root['nickname'],
                        'avatar'=> $root['headimage'],
                        'sex' => $root['sex']?$root['sex']:'',
                        'height' => $root['height'],
                        'weight' => $root['weight'],
                        'physical_activity' => $root['physical_activity'],
                        'age' => $root['age'],
                        'like_dish' => $root['like_dish'],
                        'dish_type' => $root['dish_type'],
                        'figure' => $root['figure'],
                        'taste' => $root['taste'],
                        'spend_calories' => $root['spend_calories'],
                        'headimage' => $root['headimage'],
                    ];

                    //判断是否注册百川
                    $member_uid = 'member'.$root['id'];
                    $chat_result = db('chat')->where(['userid'=>$member_uid])->find();
                    if(empty($chat_result)){
                        $result = (new \app\api\logic\Chat())->create_user($root['nickname'],'member'.$root['id'],'123456',$root['headimage'],'1',$root['id']);
                        if($result['message'] == '重复的昵称'){
                            $result = (new \app\api\logic\Chat())->create_user(time(),'member'.$root['id'],'123456',$root['headimage'],'1',$root['id']);
                        }
                        if(array_key_exists('message',$result)){
                            return array('message'=>'登陆失败');
                        }

                        $chat_result['userid'] = 'member'.$root['id'];
                        $chat_result['pwd'] = '123456';
                    }

                    $user['baichuan_user'] = $chat_result['userid'];
                    $user['baichuan_password'] = $chat_result['pwd'];

                    //背景图
                    $admin_background_image = db('admin_background_image')->find();
                    $user['background'] = $admin_background_image['background_image'];

                    //判断资料是否完善
                    if(!empty($root['headimage']) && !empty($root['nickname']) && !empty($root['sex']) && !empty($root['age']) && !empty($root['height']) && !empty($root['weight']) && !empty($root['physical_activity'])){
                        $user['is_perfect'] = 1;
                    }else{
                        $user['is_perfect'] = 0;
                    }

                    $tokenInfo = $Oauth2::generateToken($user);
                    return $tokenInfo;
            }
    }

	/*
     *	用户注册
     */
    public function register()
    {
        (new LoginValidate())->checkRegisterParam();

        $mobile   = trim($this->requestData['mobile']);
        $passwd   = trim($this->requestData['passwd']);
		$code     = trim($this->requestData['code']);
        $sex   = trim($this->requestData['sex']);
        $height   = trim($this->requestData['height']);
        $weight   = trim($this->requestData['weight']);
        $nickname   = trim($this->requestData['nickname']);
        $physical_activity   = trim($this->requestData['physical_activity']);
        $age   = trim($this->requestData['age']);
		
        if (base64_encode($code) != Cache::get('code')) {
            return array('message'=>'验证码错误');
        }else{
            if(!empty($mobile)&&!empty($passwd)){
                $where['mobile'] = $mobile;
                $whereor['nickname'] = $nickname;
                if(mb_strlen($nickname,'utf-8')>10){
                    return array('message'=>'昵称不能超过10个字');
                }

                $root = db('member')->where($where)->whereor($whereor)->find();
                if($root){
                    return array('message'=>'手机号码已注册或者该昵称已被人使用');
                }else{
                    $root = db('member')->where(array('nickname'=>$nickname))->find();
                    if(!empty($root))return array('message'=>'该昵称已被使用!');

                    $data['mobile']   = $mobile;
                    $data['passwd']   = md5($passwd);
                    $data['sex'] = $sex;
                    $data['height'] = $height;
                    $data['weight'] = $weight;
                    $data['physical_activity'] = intval($physical_activity);
                    $data['nickname'] = $nickname;
                    $data['age'] = intval($age);

                    switch ($data['physical_activity']) {
                        case '1':
                        //几乎不动(每周运动0次)
                        $brm = 1.2;
                        break;
                        case '2':
                        $brm = 1.375;
                        break;
                        case '3':
                        $brm = 1.55;
                        break;
                        case '4':
                        $brm = 1.725;
                        break;
                        case '5':
                        $brm = 1.9;
                        break;
                        default:
                        $brm =1.2;
                        break;
                    }


                    //计算卡路里
                    if($data['sex'] == '1'){
                        //男: BMR = 66 + ( 13.7 x 体重kg ) + ( 5 x 身高cm ) - ( 6.8 x 年龄years )
                        $data['spend_calories'] = 66 + (13.7 * $data['weight']) + (5 * $data['height']) - (6.8 * $data['age']);
                    }else{
                        //女: BMR = 655 + ( 9.6 x 体重kg ) + ( 1.8 x 身高cm ) - ( 4.7 x 年龄years )
                        $data['spend_calories'] = 655 + (9.6 * $data['weight']) + (1.8 * $data['height']) - (4.7 * $data['age']);
                    }

                    $data['spend_calories'] = $data['spend_calories'] * $brm;

                    Db::startTrans();
                    try{
                        $insert = db('member')->insertGetId($data);
                        if(!$insert) throw new \Exception('注册失败');

                        $result = (new \app\api\logic\Chat())->create_user($data['nickname'],'member'.$insert,'123456','http://aifood.gzldrj.com/static/uploads/20180520/2a5f98e8232764488c562651776186f0.jpg','1',$insert);
                        if(array_key_exists('message',$result)) throw new \Exception($result['message']);

                        Db::commit();
                    }catch (\Exception $e){
                        Db::rollback();
                        return array('message' => '注册失败');
                    }

                    return array();
                }
            }else{
                return array('message'=>'账号或密码为空');
            }
        } 
    }

    /*
     *  忘记密码
     */
    public function forget()
    {
        $mobile   = trim($this->requestData['mobile']);
        $passwd   = trim($this->requestData['passwd']);
        $code     = trim($this->requestData['code']);
        
        if (base64_encode($code) != Cache::get('forget')) {
            return array('message'=>'验证码错误');
        }else{
            if(!empty($mobile)&&!empty($passwd)){
                $where['mobile'] = $mobile;
                $root = db('member')->where($where)->find();
                if(!$root){
                    return array('message'=>'不存在此账户');
                }else{
                    $where['mobile']  = $mobile;
                    $data['passwd']   = md5($passwd);
                    $update = db('member')->where($where)->update($data);
                    if(!$update) return array('message'=>'修改失败');
                    return array();
                }
            }else{
                return array('message'=>'账号或密码为空');
            }
        }
    }

    /*
     *  换手机号
     */
    public function bind()
    {
        $uid      = intval($this->requestData['uid']);
        $member = checkMember($uid);
        if(!$member) return array('message'=>'此会员不存在');
        $mobile   = trim($this->requestData['mobile']);
        $code     = trim($this->requestData['code']);
        if(isset($this->requestData['passwd'])){
            $pass = trim($this->requestData['passwd']);
        }else{
            $pass = '';
        }
        
        if (base64_encode($code) != Cache::get('bind')) {
            return array('message'=>'验证码错误');
        }else{
            if(!empty($pass)){
                $password = md5($pass);
                $word = $member['passwd'];
                if($password!=$word) return array('message'=>'原密码不正确');
            }
            $data['mobile'] = $mobile;
            $member_result = db('member')->where(array('mobile'=>$mobile))->field('id')->find();
            if($member_result['id'] != $uid)return array('message'=>'该修改号码已被注册过');

            $update = db('member')->where("id='$uid'")->update($data);
            if(!$update) return array('message'=>'更改失败');
            return array();
        } 
    }
    /*
   *  启动引导
   */
    public function start()
    {
        $type     = isset($this->requestData['type'])?$this->requestData['type']:0;
        $banner = db('pic');
        if($type==0){
            $where['type']=0;
        }else{
            $where['type']=1;
        }
        $list = $banner->where($where)->select();
        foreach($list as &$v){
            $v['image']=IMG_PATH.$v['image'];
        }
        return $list;
    }
}